<!DOCTYPE html>
<?php require dirname(dirname(__FILE__)) . '/view/checkuser.php';?>
<html>
<head>
<meta charset="UTF-8">
<title>Proxy管理</title>
<link rel="stylesheet" type="text/css" href="../include/css/base.css" />
<script type="text/javascript" src="/include/js/jquery-1.9.1.js"></script>
</head>
<body>
<strong>查看：</strong>
<a href="/fetch/proxy.php?type=1">查看url列表</a> | 
<a href="/fetch/proxy.php?type=2">查看Proxy列表</a>

<strong>操作：</strong>
<a href="/fetch/proxy.php?type=1&opt=add">添加Proxy</a> | 
<a href="/fetch/proxy.php?type=2&opt=check">手动检查Proxy(每次检查20个，一般不使用)</a> | 
<!--a href="/fetch/proxy.php?type=3">Proxy写入MC</a-->
<br/><br/>

<?php
require dirname(dirname(__FILE__)) . '/include/conf.php';
require dirname(dirname(__FILE__)) . '/include/basefunc.php';
require dirname(dirname(__FILE__)) . '/include/database.php';

$CODE_MEAN = array(
	0 => 'default',
	1 => 'used',
	2 => 'http bad',
	3 => 'content bad',
	4 => 'proxy bad'
);

$opt_type = (isset($_GET['type']) && is_numeric($_GET['type'])) ? $_GET['type'] : 1;
$opt = isset($_GET['opt']) ? $_GET['opt'] : 'list';
$page = (isset($_GET['page']) && is_numeric($_GET['page'])) ? $_GET['page'] : 1;

$db = db_touzhu();

if ($opt_type == 1){
	if ($_SERVER['REQUEST_METHOD'] == 'POST'){
		// 从url抓取代理ip，并写入数据库
		$url = isset($_POST['url']) ? trim($_POST['url']) : '';
		$text = isset($_POST['text']) ? trim($_POST['text']) : '';
		if (!empty($url)){
			$_html = @file_get_contents($url);
			$proxys = extract_proxy($_html);
			
			// url入库
			$uniquemark = md5($url);
			$add_time = date('Y-m-d H:i:s');
			$sql_url_insert = "insert into proxy (type, content, uniquemark, add_time, status) 
								values(0, '{$url}', '{$uniquemark}', '{$add_time}', {$proxys['code']})";
			$db->query($sql_url_insert);
			$url_id = $db->last_id();
		}elseif (!empty($text)){
			$proxys = extract_proxy($text);
			$url_id = 0;
		}else {
			exit('提交数据错误');
		}
		
		// Proxy入库
		if ($proxys['code'] == 1){
			// 排除已经存在proxy
			$size = 20;
			$total = count($proxys['proxy']);
			$total_proxy = $total;
			$offset = 0;
			$proxy_arr = array();
			while ($offset < $total){
				$_proxys = array_slice($proxys['proxy'], $offset, $size);
				$offset += $size;
				
				$proxy_uniq = $uniq_arr = array();
				foreach ($_proxys as $_proxy){
					$uniq = md5($_proxy);
					$uniq_arr[] = '"' . $uniq . '"';
					$proxy_uniq[$uniq] = array('urlid' => $url_id, 'proxy' => $_proxy);
				}
				$sql_uniq = 'select uniquemark from proxy where type=1 and uniquemark in(' . implode(',', $uniq_arr) . ')';
				$re_uniq = $db->query($sql_uniq);
				if (!empty($re_uniq)){
					foreach ($re_uniq as $_tmp){
						$_key = $_tmp['uniquemark'];
						unset($proxy_uniq[$_key]);
					}
				}
				$proxy_arr += $proxy_uniq;
			}
			
			// 写数据库
			$size = 20;
			$total = count($proxy_arr);
			$offset = 0;
			$nowtime = date('Y-m-d H:i:s');
			$insert_proxy = $total;
			while ($offset < $total){
				$_proxys = array_slice($proxy_arr, $offset, $size);
				$offset += $size;
					
				foreach ($_proxys as $_key => $_proxy){
					$sql_insert = "insert into proxy (type, content, add_time, uniquemark, urlid)
									values(1, '{$_proxy['proxy']}', '{$nowtime}', '{$_key}', {$_proxy['urlid']})";
					$insert_re = $db->query($sql_insert);
				}
			}
			echo "Total proxy: {$total_proxy} Insert proxy: {$insert_proxy}\n";
		}else {
			echo "Error: {$CODE_MEAN[$proxys['code']]}\n";
		}
		
	}else {
		if ($opt == 'add'){
			?>
			<form action="?type=1" method="post" id="formsub">
			含Proxy的URL：
			<input type="text" name="url" id="url_con" size="100" value="" /><br>
			含Proxy的文本：
			<textarea rows="15" cols="100" name="text" id="text_con"></textarea>
			<br><br>
			<input type="submit" value=" 添 加 " />
			</form>
			<script type="text/javascript">
			$(function(){
				$("#formsub").submit(function(){
					if ($("#url_con").val() == '' && $("#text_con").val() == ''){
						alert('都是空的呀！');
						return false;
					}
				});
			});
			</script>
			<?php
		}else {
			// URL列表
			$where = 'where type=0';
			$sql_proxy = 'select count(id) as total from proxy ' . $where;
			$re_proxy = $db->query($sql_proxy);
			$total = $re_proxy[0]['total'];
			$pagesize = 20;
			$offset = ($page - 1) * $pagesize;
			$sql_proxy = "select id, content, httptime, add_time, status from proxy {$where} order by id desc limit {$offset},{$pagesize}";
			$re_proxy = $db->query($sql_proxy);
			?>
			<table class="tableunify">
				<col align="center" />
				<col align="center" />
				<col align="center" />
				<col align="center" />
				<thead>
					<tr>
						<th>ID</th>
						<th>URL</th>
						<th>ADD TIME</th>
						<th>STATUS</th>
					</tr>
				</thead>
				<tbody>
				<?php
				if (!empty($re_proxy)){
					$counter = 0;
					foreach ($re_proxy as $proxy){
						$is_alt = ($counter ++ % 2) ? ' class="alt"' : '';
						echo "<tr{$is_alt}><td>{$proxy['id']}</td><td>{$proxy['content']}</td><td>{$proxy['add_time']}</td><td>{$proxy['status']}</td></tr>\n";
					}
				}else {
					echo "<tr><td colspan=\"4\">No URL!</td></tr>\n";
				}
				?>
				</tbody>
				<tfoot>
					<tr>
					   <th class="paging" colspan="4">
					    <span>Total:<?php echo $total?> </span>
					   	<a href="/fetch/proxy.php?type=1&page=1">第一页</a> | 
					   	<a href="/fetch/proxy.php?type=1&page=<?php echo $page-1?>">上一页</a> | 
					   	<a href="/fetch/proxy.php?type=1&page=<?php echo $page+1?>">下一页</a>
					   </th>
					</tr>
				</tfoot>
			</table>
			<?php
		}
	}
	
}elseif ($opt_type == 2){
	if ($opt == 'check'){
		// 检查代理可用性，并标注连接时间
		$checktype = isset($_GET['checktype']) ? $_GET['checktype'] : '';
		if ($checktype == 'all'){
			$where = 'where type=1';
		}else {
			$where = 'where type=1 and status=0';
		}
		$sql_proxy = "select id, content, add_time, status from proxy {$where} order by id desc limit 20";
		$re_proxy = $db->query($sql_proxy);
		if (!empty($re_proxy)){
			set_time_limit(0);
			foreach ($re_proxy as $_tmp){
				$proxy = trim($_tmp['content']);
				$re = chech_proxy_bet365($proxy);
				var_dump($re);
				continue;
				
				$sql_update = "update proxy set status={$re['http_quality']}, httptime={$re['total_time']} where id={$_tmp['id']}";
				$db->query($sql_update);
			}
		}
	}else {
		$orderby = isset($_GET['orderby']) ? $_GET['orderby'] : '';
		$where = 'where type=1';
		if ($orderby == 'httptime'){
			$where .= ' and (status=1 or status=2)';
			$orderby_sql = 'order by httptime asc';
		}elseif ($orderby == 'status'){
			$where .= ' and status=0';
			$orderby_sql = 'order by status asc';
		}else {
			$orderby_sql = 'order by id desc';
		}
		$sql_proxy = 'select count(id) as total from proxy ' . $where;
		$re_proxy = $db->query($sql_proxy);
		$total = $re_proxy[0]['total'];
		$pagesize = 20;
		$offset = ($page - 1) * $pagesize;
		$sql_proxy = "select id, content, urlid, httptime, proxytype, area, add_time, status from proxy {$where} {$orderby_sql} limit {$offset},{$pagesize}";
		$re_proxy = $db->query($sql_proxy);
		?>
		<table class="tableunify">
			<col align="center" />
			<col align="center" />
			<col align="center" />
			<col align="center" />
			<thead>
				<tr>
					<th>ID</th>
					<th>PROXY</th>
					<th><a href="/fetch/proxy.php?type=2&orderby=httptime">HTTP TIME</a></th>
					<th>URLID</th>
					<th><a href="/fetch/proxy.php?type=2">ADD TIME</a></th>
					<th><a href="/fetch/proxy.php?type=2&orderby=status">STATUS</a></th>
				</tr>
			</thead>
			<tbody>
		<?php
		if (!empty($re_proxy)){
			$counter = 0;
			foreach ($re_proxy as $proxy){
				$is_alt = ($counter ++ % 2) ? ' class="alt"' : '';
				echo "<tr{$is_alt}><td>{$proxy['id']}</td><td>{$proxy['content']}</td><td>{$proxy['httptime']}</td><td>{$proxy['urlid']}</td><td>{$proxy['add_time']}</td><td>{$proxy['status']}</td></tr>\n";
			}
		}else {
			echo "<tr><td colspan=\"6\">No Proxy!</td></tr>\n";
		}
		?>
			</tbody>
			<tfoot>
				<tr>
				   <th class="paging" colspan="6">
				   	<span>Total:<?php echo $total?> </span>
				   	<a href="/fetch/proxy.php?type=2&orderby=<?php echo $orderby?>&page=1">第一页</a> | 
				   	<a href="/fetch/proxy.php?type=2&orderby=<?php echo $orderby?>&page=<?php echo $page-1?>">上一页</a> | 
				   	<a href="/fetch/proxy.php?type=2&orderby=<?php echo $orderby?>&page=<?php echo $page+1?>">下一页</a>
				   </th>
				</tr>
			</tfoot>
		</table>
		<?php
	}
}elseif ($opt_type == 3){
	// 优质代理写入MC
	$limit_p = 10;
	$sql_proxy = 'select id, content, httptime, add_time, status from proxy where type=1 and status=2 order by httptime asc limit ' . $limit_p;
	$re_proxy = $db->query($sql_proxy);
	
	$proxy_good = array();
	if (!empty($re_proxy)){
		foreach ($re_proxy as $proxy){
			$proxy_good[] = $proxy['content'];
		}
	}
	
	if (count($proxy_good) < $limit_p){
		$limit_p -= count($proxy_good);
		$sql_proxy = 'select id, content, httptime, add_time, status from proxy where type=1 and status=1 order by httptime asc limit ' . $limit_p;
		$re_proxy = $db->query($sql_proxy);
		if (!empty($re_proxy)){
			foreach ($re_proxy as $proxy){
				$proxy_good[] = $proxy['content'];
			}
		}
	}
	
	if (count($proxy_good) >= 10){
		$mem_obj = new Memcache;
		$mem_obj->connect("127.0.0.1",  11211);
		$mem_obj->set('proxys_in_mc', $proxy_good);
	}
	var_dump($proxy_good);
}


function chech_proxy_bet365($proxy){
	$url = 'https://mobile.28365365.com/navigationpages/navmenupage.aspx?navmenuid=welcome';
	$re = request_by_curl_365($url, 5, 0, $proxy, true);
	if ($re['http_code'] == 200){
		if ($re['total_time'] > 1){
			$re['http_quality'] = 1;
		}else {
			$re['http_quality'] = 2;
		}
	}else {
		$re['http_quality'] = 3;
	}
	return $re;
}

function extract_proxy($content_with_proxy){
	$code = 1;
	$content_with_proxy = trim($content_with_proxy);
	$proxys = array();
	if ($content_with_proxy){
		$reg = '/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{1,5}/';
		$match_re = preg_match_all($reg, $content_with_proxy, $matchs);
	
		if ($match_re > 0){
			foreach ($matchs[0] as $match){
				if (check_proxy($match)){
					$proxys[$match] = $match;
				}
			}
			if (empty($proxys)){
				$code = 4; // proxy bad
			}
		}else {
			$code = 3; // content bad
		}
	}else {
		$code = 2; // http bad
	}
	return array('code' => $code, 'proxy' => $proxys);
}

?>
</body>
</html>